﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Dynamics;
namespace AutumnEngine
{
    /// <summary>
    /// A scene comprises of many nodes, a camera and possibly a PhysicsSimulator.
    /// A game is made of scenes, which are made of nodes.
    /// </summary>
    public partial class Scene
    {
        public Dictionary<string, Node> Nodes;
        bool addedPhys = false;

        public Scene()
        {
            Nodes = new Dictionary<string, Node>();
            ID = Engine.LastId + 1;
            Engine.LastId = ID;
        }

        public UInt32 ID
        {
            get;
            set;
        }

        public void AddNode(string name, Node node)
        {
            if (!addedPhys)
            {
                if (Engine.Modules.Contains("Engine.PhysicsManager"))
                    Engine.Modules.PhysicsManager.AddPhysicsSimulator(this.ID);
                addedPhys = true;
            }

            node.OnAdd(name);

            
            Nodes.Add(name, node);

            Type n = node.GetType();
            if (n == typeof(PhysicsSpriteNode) || n == typeof(PhysicAnimatedSpriteNode))
            {
                //Its a physics node, add its body.
                if (Engine.Modules.Contains("Engine.PhysicsManager"))
                    Engine.Modules.PhysicsManager.AddNode(this.ID, (PhysicsSpriteNode)Nodes[name]);

            }
        }

        public void RemoveNode(string name)
        {
            Nodes.Remove(name);
        }

        public virtual void Draw()
        {
            foreach (Node n in Nodes.Values)
                n.Draw();
        }

        public virtual void Update()
        {
            if (!addedPhys)
            {
                if (Engine.Modules.Contains("Engine.PhysicsManager"))
                Engine.Modules.PhysicsManager.AddPhysicsSimulator(this.ID);
                addedPhys = true;
            }
            foreach (Node n in Nodes.Values)
                n.Update();
        }

        internal virtual void OnAdd(string name)
        {
            NameWithinEngine = name;
        }

        internal virtual void NameChanged(string to)
        {
            NameWithinEngine = to;
        }

        public string NameWithinEngine
        {
            get;
            set;
        }
    }
}
